package com.itheima.health.webcontroller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constants.MessageConstant;
import com.itheima.health.constants.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.OrderService;
import com.itheima.health.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * 预约控制层
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private OrderService orderService;


    /**
     * 发送验证码
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) {
        Result result = null;
        // 获取电话
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        // 获取redis
        Jedis jedis = jedisPool.getResource();
        // 通过手机号获取redis中的验证码
        String RedisCode = jedis.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        // 判断是否一致,或验证码是否已过期
        if (RedisCode == null || !RedisCode.equals(validateCode)) {
            // 抛出验证码错误异常
            result = new Result(false,MessageConstant.VALIDATECODE_ERROR);
            return result;
        }

        try {
            // 添加预约
            map.put("orderType",Order.ORDERTYPE_WEIXIN);
            map.put("orderStatus",Order.ORDERSTATUS_NO);
            result = orderService.addOrder(map);
            SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, (String) map.get("orderDate"));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDER_FAIL);
        }

    }

    /**
     * 根据orderId查找orderInfo
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            // 添加预约
            Map map = orderService.getOrderInfoByOrderId(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,MessageConstant.QUERY_ORDER_FAIL);
        }

    }


}
